package com.tjakus.arduino.main;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import com.tjakus.arduino.hibernate.HibernateUtil;
import com.tjakus.arduino.logging.Logging;
import com.tjakus.arduino.serial.ArduinoCommunicator;

/**
 * This is the servlet context listener which is responsible for initialization
 * and tasks scheduling
 * 
 * @author tjakus
 * 
 */

public class ApplicationInitializerListener implements ServletContextListener {

	public void contextDestroyed(ServletContextEvent arg0) {
		Logging.getLogger().info("ApplicationInitializerListener - [ contextDestroyed ] ");
		// Close serial port for communication with Arduino
		//ArduinoCommunicator.close();
	}

	/**
	 * This is the method which will be called upon application startup
	 * 
	 */

	public void contextInitialized(ServletContextEvent arg0) {
		boolean status;

		Logging.getLogger().info("ApplicationInitializerListener - [ STARTED ] ");
		// Initialize and setup connection towards database
		status = HibernateUtil.buildSessionFactory();
		if (!status) {
			Logging
					.getLogger()
					.error(
							"ApplicationInitializerListener - [ HibernateUtil initialization FAILED ] ");
			return;
		}
		// Initialize and setup serial connection to Arduino
		status = ArduinoCommunicator.initialize();
		if (!status) {
			Logging
					.getLogger()
					.error(
							"ApplicationInitializerListener - [ Arduino initialization FAILED ] ");
			return;
		}
		Logging.getLogger().info("ApplicationInitializerListener [ FINISHED ]");
	}

}
